<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .calendar {
        width: 280px;
        border: solid;
        display: flex;
        flex-wrap: wrap;
      }
      .calendar > div {
        border: solid;
        box-sizing: border-box;
        width: 40px;
        height: 40px;
      }
    </style>
  </head>
  <body>
    <div id="calendar" class="calendar">
      <div>一</div>
      <div>二</div>
      <div>三</div>
      <div>四</div>
      <div>五</div>
      <div>六</div>
      <div>日</div>
    </div>
    <script>
      function createCalendar(el, year, month) {
        // 获取当月最后一天是几号
        // 2023-6
        const date = new Date(year, month, 0).getDate();

        // 获取上月最后一天是几号
        // 2023-6
        const preDate = new Date(year, month - 1, 0).getDate();

        // 获取当月1号是星期几
        const week = new Date(year, month - 1, 1).getDay() || 7;

        // 获取当前月最后一天是星期几
        const endWeek = new Date(year, month, 0).getDay();

        console.log(preDate);
        //根据当月第一天星期补空
        for (let i = week - 2; i >= 0; i--) {
          const div = document.createElement("div");
          div.innerHTML = preDate - i;
          el.append(div);
        }
        // 创建主体日期
        for (let i = 1; i <= date; i++) {
          const div = document.createElement("div");
          div.innerHTML = i;
          el.append(div);
        }

        //根据当月最后一天星期补空
        for (let i = 1; i <= 7 - endWeek; i++) {
          const div = document.createElement("div");
          div.innerHTML = i;
          el.append(div);
        }
      }
      const calendar = document.getElementById("calendar");
      createCalendar(calendar, 2023, 8);
    </script>
  </body>
</html>
